package org.example.price.controller;


import org.example.feign.feignClient.PojoServiceClient;
import org.example.feign.pojo.MyEntity;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@CrossOrigin(origins = "*")
@Controller
@RestController
public class NewPriceController {
    private final ResourceLoader resourceLoader;
    private final PojoServiceClient pojoServiceClient;

    public NewPriceController(ResourceLoader resourceLoader, PojoServiceClient pojoServiceClient) {
        this.resourceLoader = resourceLoader;
        this.pojoServiceClient = pojoServiceClient;
    }

    @PostMapping("/form")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @RequestParam("price") String price, @RequestParam("describe") String describe) {
        try {
            // 获取static/source文件夹的绝对路径
            Resource resource = resourceLoader.getResource("classpath:static/price/");
            File sourceDir = resource.getFile();
            // 保存文件到本地路径
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(sourceDir+"//"+ file.getOriginalFilename());
                System.out.println(path);
                Files.write(path, bytes);
            }
            // 创建并保存MyEntity对象到数据库
            MyEntity entity = new MyEntity();
            String imageUrl = "http://localhost:8087/price/" +file.getOriginalFilename();
            entity.setName(name);
            entity.setPrice(price);
            entity.setDescribe(describe);
            entity.setImageURL(imageUrl);
            System.out.println(entity);

            String result = pojoServiceClient.newprice(entity);
            System.out.println(result);

            return new ResponseEntity<>("文件上传成功！信息已保存到数据库。", HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败：" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
}